package com.xiaoyuer.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xiaoyuer.yygh.cmn.listener.DictListener;
import com.xiaoyuer.yygh.cmn.mapper.DictMapper;
import com.xiaoyuer.yygh.cmn.service.DictService;
import com.xiaoyuer.yygh.common.util.CopyUtis;
import com.xiaoyuer.yygh.model.entity.cmn.Dict;
import com.xiaoyuer.yygh.model.vo.DictDataVo;
import com.xiaoyuer.yygh.model.vo.DictEeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {
     //   List<Dict> dictList = dictMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", id));
        List<Dict> dictList = dictMapper.selectListById(id);
        dictList.forEach(dict -> {
            dict.setHasChildren(this.isChildren(dict.getId()));
        });
        return dictList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            List<Dict> dictList = dictMapper.selectList(null);
            List<DictEeVo> dictEeVoList = CopyUtis.copy(dictList, DictEeVo.class);
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<DictDataVo> dictTree() {
        //先查询所有的数据字典
        List<Dict> dictList = dictMapper.selectList(null);
        List<DictDataVo> dictEeVoList = CopyUtis.copy(dictList, DictDataVo.class);


        //获取父级数据字典
        List<DictDataVo> dataVos = dictEeVoList.stream().filter(e -> e.getParentId()==1).map(e -> {
            e.setTreeChildren(getChildrens(e, dictEeVoList));
            return e;
        }).collect(Collectors.toList());
        return  dataVos;
    }

    @Override
    @CacheEvict(value = "dict", allEntries=true)
    public void importData(MultipartFile file) {

        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断id下面是否有子节点
    private Boolean isChildren(Long id){
        //Integer count = dictMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id));
        List<Dict> dicts = dictMapper.selectListById(id);
        return dicts.size()>0;
    }

    /**
     * 递归查询子节点
     * @param dict
     * @param dictList
     * @return
     */
    private List<DictDataVo> getChildrens(DictDataVo dict,List<DictDataVo> dictList){
        List<DictDataVo> childrenList = dictList.stream().filter(e -> Objects.equals(e.getParentId(), dict.getId())).map(e -> {
            e.setTreeChildren(getChildrens(e, dictList));
            return e;
        }).collect(Collectors.toList());
        return childrenList;
    }
}
